package com.itheima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias.mapper.ClazzMapper;
import com.itheima.tlias.pojo.Clazz;
import com.itheima.tlias.pojo.PageResult;
import com.itheima.tlias.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
	@Autowired
	private ClazzMapper clazzMapper;


	@Override
	public List<Clazz> list() {
		return clazzMapper.list();
	}

	@Override
	public void save(Clazz clazz) {
		clazz.setCreateTime(LocalDateTime.now());
		clazz.setUpdateTime(LocalDateTime.now());
		clazzMapper.save(clazz);
	}

	@Override
	public Clazz getById(Integer id) {
		//clazz.setStatus(LocalDate.now().isAfter(oldClazz.getEndDate()) ? "已开课" : "未开课");
		return clazzMapper.getById(id);
	}

	@Override
	public void updateById(Clazz clazz) {
		Clazz oldClazz = clazzMapper.getById(clazz.getId());
		if (oldClazz == null) throw new RuntimeException("没有id为" + clazz.getId() + "的班级，更新失败");
		clazz.setUpdateTime(LocalDateTime.now());

		clazzMapper.updateById(clazz);
	}

	@Override
	public PageResult<Clazz> page(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
		PageHelper.startPage(page, pageSize);

		List<Clazz> list = clazzMapper.page(name, begin, end, page, pageSize);
		//list.forEach(clazz -> clazz.setStatus(LocalDate.now().isAfter(clazz.getEndDate()) ? "已开课" : "未开课"));
		Page<Clazz> clazzPage = (Page<Clazz>) list;
		return new PageResult<>(clazzPage.getTotal(), clazzPage.getResult());
	}

	@Override
	public void deleteById(Integer id) {
		clazzMapper.deleteById(id);
	}


}
